package com.eshop.controller;

import com.eshop.pojo.OrderDetail;
import com.eshop.pojo.OrderInfo;
import com.eshop.pojo.Pager;
import com.eshop.service.OrderInfoService;

import com.eshop.service.ProductInfoService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import com.google.gson.JsonParseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/order")
public class OrderInfoController {
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private ProductInfoService productInfoService;

    @RequestMapping("/commitOrder")
    @ResponseBody
    public String commitOrder(String inserted, String orderInfo) throws JsonParseException, JsonMappingException, IOException{
        try {
            //创建ObjectMapper对象，实现JavaBean和Json的转换
            ObjectMapper objectMapper = new ObjectMapper();
            //设置输入时忽略在JSON字符串中存在但在JAVA对象中没有的属性
            objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
            //将JSON字符串orderInfo转换成JavaBean对象（主表）
            OrderInfo o = objectMapper.readValue(orderInfo, OrderInfo[].class)[0];
            //保存订单信息
            orderInfoService.saveOderInfo(o);
            //将JSON字符串转换成List<OrderDetail>集合（副表）
            List<OrderDetail> orderDetailList = objectMapper.readValue(inserted, new TypeReference<ArrayList<OrderDetail>>(){});
            //保存订单明细
            for (OrderDetail temp : orderDetailList){
                temp.setOid(o.getId());//设置关联的订单号
                orderInfoService.saveOrderDetail(temp);
                //扣减库存
                productInfoService.sell(temp.getPid(),temp.getNum());
            }
            return "success";
        } catch (IOException e) {
            e.printStackTrace();
            return "failure";
        }
    }

    @ResponseBody
    @RequestMapping("/searchOrder")
    public Map<String,Object> searchOrder(int rows, int page, OrderInfo orderInfo){
        //System.out.println("---------"+orderInfo);//调试
        Pager pager = new Pager();
        pager.setPerPageRows(rows);
        pager.setCurPage(page);
        //封装查询条件
        Map<String,Object>params = new HashMap<>();
        params.put("orderInfo", orderInfo);
        int count = orderInfoService.count(params);//获取满足条件的订单总数
        List<OrderInfo> orderInfoList = orderInfoService.selectByPage(orderInfo,pager);//获取满足条件的订单列表
        //System.out.println("count="+count+",,"+"orderInfoList.size()="+orderInfoList.size());//调试
        //封装返回条件
        Map<String,Object> map = new HashMap<>();
        map.put("total",count);
        map.put("rows",orderInfoList);
        return map;
    }

    @RequestMapping(value = "/deleteOrder",produces = "text/html;charset=UTF-8" )
    @ResponseBody
    public String deleteOrder(@RequestParam(value = "oids",required = false) String oids){
        String[] id = oids.split(",");//将包含逗号的字符串以逗号为标志，分割成多个字符串，将结果以字符串数组返回
        int count = 0;
        try {
            for(String i : id){
                count += orderInfoService.deleteOrder(Integer.parseInt(i));
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return "{\"success\":\"false\",\"message\":\"删除失败！\"}";
        }
        return "{\"success\":\"true\",\"message\":\"份订单删除成功！\",\"count\":"+count+"}";
    }

    @RequestMapping("/getOrderInfo")
    public String getOrderInfo(int oid, Model model){
        OrderInfo orderInfo = orderInfoService.selectOrderInfoById(oid);
        model.addAttribute("orderInfo",orderInfo);
        return "orderDetail";//页面
    }

    @RequestMapping("/getOrderDetail")
    @ResponseBody
    public List<OrderDetail> getOrderDetail(@RequestParam("oid") int oid){
        List<OrderDetail> orderDetailList = orderInfoService.selectOrderDetailByOid(oid);
        for (OrderDetail o : orderDetailList){
            o.setTotalprice( o.getPi().getPrice() * o.getNum() );//设置小计
            o.setPrice( o.getPi().getPrice() );//设置单价
        }
        return orderDetailList;
    }

    @RequestMapping("/statisticalOrder")
    @ResponseBody
    public Map<String,Object> statisticalOrder(int rows, int page, OrderInfo orderInfo){
        //System.out.println("---------"+orderInfo);//调试
        Pager pager = new Pager();
        pager.setPerPageRows(rows);
        pager.setCurPage(page);
        //封装查询条件
        Map<String,Object>params = new HashMap<>();
        params.put("orderInfo", orderInfo);
        int count = orderInfoService.count(params);//获取满足条件的订单总数
        List<OrderInfo> orderInfoList = orderInfoService.selectByPage(orderInfo,pager);//获取满足条件的订单列表
        //System.out.println("count="+count+",,"+"orderInfoList.size()="+orderInfoList.size());//调试
        //封装返回条件
        Map<String,Object> map = new HashMap<>();
        map.put("total",count);
        map.put("rows",orderInfoList);
        return map;
    }
}
